
import time
import json
import hmac
import base64
import urllib
import hashlib
import logging
import requests

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s:%(name)s:%(levelname)s: %(message)s')

class Common(object):

    def __init__(self):

        pass

    def __dingtalk_robot_signature(self, secret):
        timestamp = int(round(time.time() * 1000))
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        logging.info("timestamp: %s, sign: %s" % (timestamp, sign))
        return timestamp, sign

    def dingtalk_robot(self, secret, access_token, text, title, picUrl, messageUrl):
        signature = self.__dingtalk_robot_signature(secret)
        timestamp = signature[0]
        sign = signature[1]

        url = "https://oapi.dingtalk.com/robot/send?access_token={}&timestamp={}&sign={}".format(access_token, timestamp, sign)
        headers = {
            "Content-Type": "application/json"
        }

        body = {
            "msgtype": "link",
            "link": {
                "text": text,
                "title": title,
                "picUrl": picUrl,
                "messageUrl": messageUrl
            }
        }

        res = requests.post(url=url, headers=headers, data=json.dumps(body))
        logging.info('Dingtalk status_code: %s, text: %s' % (res.status_code, res.text))

